<template>
  <div class="attractions-map-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">
        <el-icon><MapLocation /></el-icon>
        景点地图总览
      </h1>
      <p class="page-subtitle">在地图上浏览所有景点，直观了解景点分布</p>
    </div>

    <el-row :gutter="20">
      <!-- 左侧：筛选和列表 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="6">
        <el-card class="filter-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><FilterIcon /></el-icon>
              <span>筛选条件</span>
            </div>
          </template>

          <!-- 分类筛选 -->
          <el-form label-width="80px" size="default">
            <el-form-item label="景点分类">
              <el-select
                v-model="selectedCategory"
                placeholder="全部分类"
                clearable
                style="width: 100%"
                @change="handleCategoryChange"
              >
                <el-option label="全部" value="" />
                <el-option label="文化古迹" value="cultural" />
                <el-option label="自然风光" value="natural" />
                <el-option label="现代建筑" value="modern" />
                <el-option label="美食购物" value="food" />
              </el-select>
            </el-form-item>

            <el-form-item label="价格范围">
              <el-slider
                v-model="priceRange"
                range
                :min="0"
                :max="500"
                :step="10"
                show-stops
                :show-tooltip="true"
                @change="handlePriceChange"
              />
              <div class="price-display">
                ¥{{ priceRange[0] }} - ¥{{ priceRange[1] }}
              </div>
            </el-form-item>

            <el-form-item label="搜索景点">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索景点名称..."
                clearable
                @input="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-form>

          <!-- 景点列表 -->
          <el-divider>景点列表 ({{ filteredAttractions.length }})</el-divider>
          <div class="attractions-list">
            <div
              v-for="attraction in filteredAttractions"
              :key="attraction.id"
              class="attraction-item"
              :class="{ active: selectedAttraction?.id === attraction.id }"
              @click="selectAttraction(attraction)"
            >
              <div class="item-image">
                <el-image
                  v-if="attraction.primary_image"
                  :src="getImageUrl(attraction.primary_image)"
                  fit="cover"
                  lazy
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><PictureRounded /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div v-else class="no-image">
                  <el-icon><PictureRounded /></el-icon>
                </div>
              </div>
              <div class="item-content">
                <h4 class="item-name">{{ attraction.name }}</h4>
                <div class="item-info">
                  <el-tag :type="getCategoryType(attraction.category)" size="small">
                    {{ attraction.category_display }}
                  </el-tag>
                  <span class="item-price">¥{{ attraction.ticket_price }}</span>
                </div>
                <div class="item-rating">
                  <el-rate
                    :model-value="(attraction.rating || 0) / 1"
                    disabled
                    size="small"
                    show-score
                    text-color="#ff9900"
                    score-template="{value}"
                  />
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：地图 -->
      <el-col :xs="24" :sm="24" :md="16" :lg="18">
        <el-card class="map-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>景点分布地图</span>
              <div class="map-controls">
                <el-button size="small" :icon="RefreshRight" @click="refreshMap">
                  刷新地图
                </el-button>
                <el-button size="small" :icon="FullScreenIcon" @click="fitView">
                  适应视野
                </el-button>
              </div>
            </div>
          </template>

          <div v-loading="mapLoading" id="attractions-map" class="map-container"></div>

          <!-- 地图图例 -->
          <div class="map-legend">
            <div class="legend-item">
              <span class="legend-marker cultural"></span>
              <span>文化古迹</span>
            </div>
            <div class="legend-item">
              <span class="legend-marker natural"></span>
              <span>自然风光</span>
            </div>
            <div class="legend-item">
              <span class="legend-marker modern"></span>
              <span>现代建筑</span>
            </div>
            <div class="legend-item">
              <span class="legend-marker food"></span>
              <span>美食购物</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  MapLocation,
  Filter as FilterIcon,
  Search,
  RefreshRight,
  FullScreen as FullScreenIcon,
  PictureRounded
} from '@element-plus/icons-vue'
import TravelAPI from '../api/travel'
import { AMapUtil } from '../utils/amap'
import logger from '../utils/logger'
import { getImageUrl as getImageUrlUtil } from '../utils/apiConfig'

export default {
  name: 'AttractionsMap',
  components: {
    MapLocation,
    FilterIcon,
    Search,
    PictureRounded
  },
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const mapLoading = ref(false)
    const attractions = ref([])
    const selectedCategory = ref('')
    const priceRange = ref([0, 500])
    const searchKeyword = ref('')
    const selectedAttraction = ref(null)
    const amapUtil = ref(null)

    // 筛选后的景点列表
    const filteredAttractions = computed(() => {
      let result = attractions.value

      // 分类筛选
      if (selectedCategory.value) {
        result = result.filter(attr => attr.category === selectedCategory.value)
      }

      // 价格筛选
      result = result.filter(attr => {
        const price = attr.ticket_price || 0
        return price >= priceRange.value[0] && price <= priceRange.value[1]
      })

      // 搜索筛选
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        result = result.filter(attr =>
          attr.name.toLowerCase().includes(keyword) ||
          (attr.address && attr.address.toLowerCase().includes(keyword))
        )
      }

      return result
    })

    // 获取景点列表
    const fetchAttractions = async () => {
      loading.value = true
      try {
        const response = await TravelAPI.getAttractions()
        attractions.value = response.results || response
      } catch (error) {
        logger.error('获取景点列表失败:', error)
        ElMessage.error('获取景点列表失败')
      } finally {
        loading.value = false
      }
    }

    // 初始化地图
    const initMap = async () => {
      mapLoading.value = true
      try {
        const apiKey = process.env.VUE_APP_AMAP_KEY || ''
        if (!apiKey || apiKey === 'your_amap_api_key') {
          ElMessage.warning('高德地图API Key未配置，地图功能不可用')
          mapLoading.value = false
          return
        }

        if (!amapUtil.value) {
          amapUtil.value = new AMapUtil(apiKey)
        }

        // 等待DOM渲染
        await new Promise(resolve => setTimeout(resolve, 300))

        // 计算中心点（所有景点的平均位置）
        if (attractions.value.length > 0) {
          const centerLng = attractions.value.reduce(
            (sum, attr) => sum + parseFloat(attr.longitude || 115.89),
            0
          ) / attractions.value.length

          const centerLat = attractions.value.reduce(
            (sum, attr) => sum + parseFloat(attr.latitude || 28.68),
            0
          ) / attractions.value.length

          await amapUtil.value.initMap('attractions-map', {
            center: [centerLng, centerLat],
            zoom: 12
          })

          // 添加所有景点标记
          updateMapMarkers()
        } else {
          // 默认南昌市中心
          await amapUtil.value.initMap('attractions-map', {
            center: [115.89, 28.68],
            zoom: 12
          })
        }
      } catch (error) {
        logger.error('地图初始化失败:', error)
        ElMessage.error('地图加载失败')
      } finally {
        mapLoading.value = false
      }
    }

    // 更新地图标记
    const updateMapMarkers = () => {
      if (!amapUtil.value || !amapUtil.value.map) return

      const markers = filteredAttractions.value.map(attr => {
        const categoryColors = {
          cultural: '#E6A23C', // 橙色
          natural: '#67C23A',   // 绿色
          modern: '#409EFF',    // 蓝色
          food: '#F56C6C'       // 红色
        }

        const color = categoryColors[attr.category] || '#909399'

        const infoContent = `
          <div style="padding: 10px; min-width: 200px;">
            <h3 style="margin: 0 0 10px 0; color: ${color};">${attr.name}</h3>
            <p style="margin: 5px 0;"><strong>分类:</strong> ${attr.category_display || '未知'}</p>
            <p style="margin: 5px 0;"><strong>地址:</strong> ${attr.address || '暂无'}</p>
            <p style="margin: 5px 0;"><strong>门票:</strong> ¥${attr.ticket_price}</p>
            <p style="margin: 5px 0;"><strong>评分:</strong> ${attr.rating || 0}</p>
            <div style="margin-top: 10px;">
              <button onclick="window.viewAttractionDetail(${attr.id})" 
                      style="background: #409EFF; color: white; border: none; padding: 5px 15px; border-radius: 4px; cursor: pointer;">
                查看详情
              </button>
            </div>
          </div>
        `

        return {
          lng: parseFloat(attr.longitude || 115.89),
          lat: parseFloat(attr.latitude || 28.68),
          title: attr.name,
          info: infoContent,
          category: attr.category
        }
      })

      amapUtil.value.addMarkers(markers)

      // 设置全局函数供信息窗口调用
      window.viewAttractionDetail = (id) => {
        router.push(`/attractions/${id}`)
      }
    }

    // 选择景点
    const selectAttraction = (attraction) => {
      selectedAttraction.value = attraction
      // 在地图上定位到该景点
      if (amapUtil.value && amapUtil.value.map) {
        amapUtil.value.map.setCenter([
          parseFloat(attraction.longitude),
          parseFloat(attraction.latitude)
        ])
        amapUtil.value.map.setZoom(15)
      }
    }

    // 筛选变化处理
    const handleCategoryChange = () => {
      updateMapMarkers()
    }

    const handlePriceChange = () => {
      updateMapMarkers()
    }

    const handleSearch = () => {
      updateMapMarkers()
    }

    // 刷新地图
    const refreshMap = () => {
      updateMapMarkers()
    }

    // 适应视野
    const fitView = () => {
      if (amapUtil.value && amapUtil.value.map && amapUtil.value.markers.length > 0) {
        amapUtil.value.map.setFitView(amapUtil.value.markers)
      }
    }

    // 获取图片URL
    const getImageUrl = (url) => {
      return getImageUrlUtil(url)
    }

    // 获取分类类型
    const getCategoryType = (category) => {
      const types = {
        'cultural': 'warning',
        'natural': 'success',
        'modern': 'info',
        'food': 'danger'
      }
      return types[category] || 'info'
    }

    // 监听筛选变化
    watch(filteredAttractions, () => {
      updateMapMarkers()
    })

    onMounted(async () => {
      await fetchAttractions()
      await initMap()
    })

    onUnmounted(() => {
      if (amapUtil.value) {
        amapUtil.value.destroy()
      }
      if (window.viewAttractionDetail) {
        delete window.viewAttractionDetail
      }
    })

    return {
      loading,
      mapLoading,
      attractions,
      selectedCategory,
      priceRange,
      searchKeyword,
      selectedAttraction,
      filteredAttractions,
      selectAttraction,
      handleCategoryChange,
      handlePriceChange,
      handleSearch,
      refreshMap,
      fitView,
      getImageUrl,
      getCategoryType,
      RefreshRight,
      FullScreenIcon
    }
  }
}
</script>

<style scoped>
.attractions-map-page {
  /* 南昌旅游特色：天空蓝渐变背景 */
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 50%, #90CAF9 100%);
  min-height: 100vh;
  padding: clamp(10px, 2vw, 20px);
  animation: fadeIn 0.5s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.attractions-map-page {
  max-width: 1600px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
  padding: 30px 20px;
  background: linear-gradient(135deg, rgba(255,255,255,0.9) 0%, rgba(227,242,253,0.7) 100%);
  border-radius: 16px;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 20px rgba(200, 16, 46, 0.1);
  position: relative;
  text-align: center;
}

.page-header::before {
  content: '';
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  bottom: -2px;
  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 50%, #1E88E5 100%);
  border-radius: 16px;
  z-index: -1;
  opacity: 0.3;
  filter: blur(8px);
}

.page-title {
  font-size: clamp(24px, 4vw, 36px);
  font-weight: 700;
  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.page-title .el-icon {
  font-size: 1.2em;
  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.page-subtitle {
  font-size: clamp(14px, 2vw, 18px);
  color: #606266;
  font-weight: 500;
  letter-spacing: 0.5px;
}

.filter-card {
  height: calc(100vh - 200px);
  overflow-y: auto;
  border-radius: 16px;
  border: 1px solid rgba(200, 16, 46, 0.12);
  background: linear-gradient(135deg, rgba(255,255,255,0.98) 0%, rgba(227,242,253,0.85) 100%);
  backdrop-filter: blur(12px);
  box-shadow: 0 4px 20px rgba(200, 16, 46, 0.08), 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.filter-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #C8102E 0%, #D4AF37 50%, #1E88E5 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.filter-card:hover::before {
  opacity: 1;
}

.filter-card:hover {
  box-shadow: 0 12px 32px rgba(200, 16, 46, 0.15), 0 4px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-4px);
  border-color: rgba(212, 175, 55, 0.4);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
  font-size: 16px;
  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.card-header .el-icon {
  margin-right: 8px;
  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.map-controls {
  display: flex;
  gap: 10px;
}

.map-controls .el-button {
  transition: all 0.3s ease;
}

.map-controls .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(200, 16, 46, 0.2);
}

.price-display {
  text-align: center;
  color: #606266;
  font-size: 14px;
  font-weight: 600;
  margin-top: 8px;
  padding: 8px;
  background: linear-gradient(135deg, rgba(200, 16, 46, 0.05) 0%, rgba(212, 175, 55, 0.05) 100%);
  border-radius: 8px;
  border: 1px solid rgba(200, 16, 46, 0.1);
}

.attractions-list {
  max-height: calc(100vh - 400px);
  overflow-y: auto;
}

.attraction-item {
  display: flex;
  padding: 14px;
  margin-bottom: 12px;
  border: 1px solid rgba(200, 16, 46, 0.12);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  background: linear-gradient(135deg, rgba(255,255,255,0.95) 0%, rgba(227,242,253,0.7) 100%);
  backdrop-filter: blur(8px);
  box-shadow: 0 2px 8px rgba(200, 16, 46, 0.06);
  position: relative;
  overflow: hidden;
}

.attraction-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background: linear-gradient(180deg, #C8102E 0%, #D4AF37 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.attraction-item:hover::before {
  opacity: 1;
}

.attraction-item:hover {
  box-shadow: 0 6px 20px rgba(200, 16, 46, 0.15);
  transform: translateX(6px);
  border-color: rgba(212, 175, 55, 0.4);
}

.attraction-item.active {
  background: linear-gradient(135deg, rgba(200, 16, 46, 0.12) 0%, rgba(212, 175, 55, 0.12) 100%);
  border-color: #C8102E;
  box-shadow: 0 6px 20px rgba(200, 16, 46, 0.25);
  transform: translateX(6px);
}

.attraction-item.active::before {
  opacity: 1;
  width: 4px;
}

.item-image {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  overflow: hidden;
  flex-shrink: 0;
  margin-right: 10px;
}

.item-image .el-image,
.item-image .no-image {
  width: 100%;
  height: 100%;
}

.no-image {
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
}

.image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #c0c4cc;
}

.item-content {
  flex: 1;
  min-width: 0;
}

.item-name {
  margin: 0 0 8px 0;
  font-size: 15px;
  font-weight: 600;
  background: linear-gradient(135deg, #303133 0%, #606266 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  transition: all 0.3s ease;
}

.attraction-item:hover .item-name,
.attraction-item.active .item-name {
  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.item-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 5px;
}

.item-price {
  font-weight: 700;
  font-size: 15px;
  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.item-rating {
  display: flex;
  align-items: center;
}

.map-card {
  height: calc(100vh - 200px);
  border-radius: 16px;
  border: 1px solid rgba(200, 16, 46, 0.12);
  background: linear-gradient(135deg, rgba(255,255,255,0.98) 0%, rgba(227,242,253,0.85) 100%);
  backdrop-filter: blur(12px);
  box-shadow: 0 4px 20px rgba(200, 16, 46, 0.08), 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.map-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #C8102E 0%, #D4AF37 50%, #1E88E5 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: 1;
}

.map-card:hover::before {
  opacity: 1;
}

.map-card:hover {
  box-shadow: 0 12px 32px rgba(200, 16, 46, 0.15), 0 4px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
  border-color: rgba(212, 175, 55, 0.4);
}

.map-container {
  width: 100%;
  height: calc(100vh - 300px);
  min-height: 500px;
  border-radius: 12px;
  overflow: hidden;
  border: 2px solid rgba(200, 16, 46, 0.15);
  box-shadow: 0 8px 24px rgba(200, 16, 46, 0.12), 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
}

.map-container::before {
  content: '';
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  bottom: -2px;
  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 50%, #1E88E5 100%);
  border-radius: 12px;
  z-index: -1;
  opacity: 0.2;
  filter: blur(8px);
}

.map-container:hover {
  box-shadow: 0 12px 32px rgba(200, 16, 46, 0.2), 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: rgba(212, 175, 55, 0.4);
}

.map-legend {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-top: 20px;
  padding: 16px;
  background: linear-gradient(135deg, rgba(255,255,255,0.9) 0%, rgba(227,242,253,0.7) 100%);
  border-radius: 12px;
  border-top: 2px solid rgba(200, 16, 46, 0.1);
  backdrop-filter: blur(8px);
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  font-weight: 500;
  color: #606266;
  padding: 6px 12px;
  border-radius: 8px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.legend-item:hover {
  background: rgba(200, 16, 46, 0.05);
  transform: translateY(-2px);
}

.legend-marker {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  border: 3px solid white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2), 0 0 0 2px rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
}

.legend-item:hover .legend-marker {
  transform: scale(1.2);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3), 0 0 0 3px rgba(255, 255, 255, 0.9);
}

.legend-marker.cultural {
  background-color: #E6A23C;
}

.legend-marker.natural {
  background-color: #67C23A;
}

.legend-marker.modern {
  background-color: #409EFF;
}

.legend-marker.food {
  background-color: #F56C6C;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .attractions-map-page {
    padding: 10px;
  }

  .page-header {
    padding: 20px 15px;
  }

  .page-title {
    font-size: 24px;
    flex-direction: column;
    gap: 8px;
  }

  .filter-card {
    height: auto;
    margin-bottom: 20px;
    max-height: 500px;
  }

  .map-card {
    height: 500px;
  }

  .map-container {
    height: 400px;
    min-height: 400px;
  }

  .map-legend {
    flex-wrap: wrap;
    gap: 12px;
  }

  .attraction-item {
    padding: 12px;
  }
}
</style>

